/**
 * Copyright (C) 2022 - 长期
 * All rights reserved.
 * <p>
 *     */
package com.itzhoun.config.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhounan
 * @date 2024/01/22 14:31
 * @Description
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());



    /**
     *
     * @author zhounan
     * @Create 2024/1/22 22:04
     * @Description 判断用户头部是否包含Authorization字段即可
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader("Authorization");
        return StringUtils.isNotBlank(authorization);
    }


    /**
     *
     * @author zhounan
     * @Create 2024/1/23 20:45
     * @Description  登录操作
     * @param request 入参
     * @param response 响应
     * @return boolean
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        JWTToken jwtToken = new JWTToken(token);
        //提交给realm进行登入，如果错位他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     *
     * @author zhounan
     * @Create 2024/1/23 20:32
     * @Description 这里我们详细说明下为啥最终返回的都是true，即允许访问
     * 因为游客和访客看到的内容是不同的
     * 如果在这里返回了false 请求会被直接拦截，用户看不到任务内容
     * 所以我们这里返回了true, Controller可以通过subject.isAuthenticated()来判断用户是否登入
     * 如果有些资源只有登入用户才能访问，我们只需要在方法上加入@RequiresAuthentication注解即可
     * 但是这样做有一个缺点，就是不能够对Get、POST等请求进行分别过滤鉴权，但实际上对应用影响不大
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)){
            return executeLogin(request, response);
        }
        return true;
    }

    /**
     *
     * @author zhounan
     * @Create 2024/1/23 20:39
     * @Description 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


    /**
     *
     * @author zhounan
     * @Create 2024/1/23 20:44
     * @Description 将非法请求 /401
     * @param request 请求
     * @param response 响应
     */
    private void response401(ServletRequest request, ServletResponse response){
        try {
            HttpServletResponse response1 = (HttpServletResponse) response;
            response1.sendRedirect("/401");
        }catch (IOException e){
            logger.error(e.getMessage());
        }
    }
}
